<!-- 基础表格 -->
<template>
  <div class="parent">
    <div class="title">
      用户列表
    </div>
    <!-- 搜索区域 -->
    <ArtSearchBar style="margin-top: 10px;" v-model:filter="searchFormState" :items="searchItems" :is-expand="false"
      :show-expand="true" @search="handleSearch" @reset="handleReset" />
    <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
      <!-- 表格 -->
      <el-button type="primary" @click.stop="clickAdd()">新增用户</el-button>
      <el-dialog v-model="dialogFormVisible" :title="form.id ? '修改' : '新增'">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="form.username" placeholder="输入用户名" clearable />
          </el-form-item>
          <el-form-item label="真实姓名" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" placeholder="输入真实姓名" clearable />
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色" clearable @click.stop style="width: 100%;">
              <el-option label="超管(SUPER)" value="SUPER" />
              <el-option label="用户(USER)" value="USER" />
            </el-select>
          </el-form-item>
          <el-form-item label="套餐失效时间" :label-width="formLabelWidth" prop="orderCloseTime">
            <el-date-picker format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
              v-model="form.orderCloseTime" type="datetime" placeholder="选择套餐失效时间" />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="orderCloseTime">
            <el-input type="password" show-password v-model="form.password" placeholder="密码变更" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="save(ruleFormRef)">
              确认修改
            </el-button>
          </span>
        </template>
      </el-dialog>

      <ArtTable rowKey="id" :show-table-header="false" :loading="loading" :data="tableData" :columns="columns"
        :pagination="pagination" @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange">

        <!-- 告警状态列 -->
        <template #alarmIng="{ row }">
          <div class="">
            <el-tag v-if="row.alarmIng == '1'" style="color:#ffffff" color="red">紧急告警</el-tag>
            <el-tag v-else-if="row.alarmIng == '2'" class="" type="danger">告警</el-tag>
            <el-tag v-else-if="row.alarmIng == '3'" class="" type="warning">预警</el-tag>
            <el-tag v-else class="" type="success">正常</el-tag>
          </div>
        </template>
        <!-- 在线状态列 -->
        <template #online="{ row }">
          <div class="">
            <el-tag v-if="row.online == '1'" type="success">在线</el-tag>
            <el-tag v-else class="info">离线</el-tag>
          </div>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="operation-buttons">
            <ArtButtonTable type="edit" :row="row" @click="clickEdit(row)" />
            <el-popconfirm class="box-item" title="确定要删除吗" placement="top" @confirm="del(row.id)">
              <template #reference>
                <ArtButtonTable type="delete" />
              </template>
            </el-popconfirm>
          </div>
        </template>
      </ArtTable>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import { useTable } from '@/composables/useTable'
import { BmslzService } from '@/api/bmslzApi'
import type { SearchFormItem } from '@/types'
import { router } from '@/router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  username: string
  name: string
  role: string
}
const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '真实姓名要在50个字符内', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '真实姓名不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '真实姓名要在50个字符内', trigger: 'blur' },],
  role: [
    { required: true, message: '角色不能为空', trigger: 'blur' }],
})

defineOptions({ name: 'UserMixedUsageExample' })

const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const form = ref<any>({ id: '' })

const save = async (formEl: FormInstance | undefined) => {
  let returnT = ref<boolean>(false);
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('数据填写不完整');
      returnT.value = true
    }
  })
  if (returnT.value) {
    return
  }
  //修改或新增用户
  const { data } = await BmslzService.userSave(form.value)
  ElMessage.success('操作成功！');
  dialogFormVisible.value = false
  handleSearch();
}
const del = async (id: any) => {
  const data = await BmslzService.userDel({
    id
  })
  ElMessage.success('操作成功！');
  handleSearch();
}
const clickAdd = () => {
  dialogFormVisible.value = true
  form.value = { id: null };
}
const clickEdit = (row: any) => {
  dialogFormVisible.value = true
  form.value = row;
}
// 表单搜索初始值
const defaultFilter = ref({
  projectName: '',
  projectNo: '',
  online: '',
})

// 搜索表单状态
const searchFormState = ref({ ...defaultFilter.value })

const searchItems: SearchFormItem[] = [
  {
    prop: 'id',
    label: '用户id',
    type: 'input',
    config: {
      placeholder: '请输入用户id',
      clearable: true
    }
  },
  {
    prop: 'username',
    label: '用户名',
    type: 'input',
    config: {
      placeholder: '请输入用户名',
      clearable: true
    }
  },
  {
    prop: 'orderCloseTime',
    label: '失效时间',
    type: 'daterange',
    config: {
      type: 'daterange',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      clearable: true
    }
  }, {
    prop: 'name',
    label: '真实姓名',
    type: 'input',
    config: {
      placeholder: '请输入真实姓名',
      clearable: true
    }
  }
]
const handleReset = () => {
  // 重置搜索表单状态
  searchFormState.value = { ...defaultFilter.value }
  resetSearch()
}
const handleSearch = () => {
  console.log('搜索参数:', searchFormState.value)
  const { ...searchParams } = searchFormState.value

  // 搜索参数赋值
  Object.assign(searchState, { ...searchParams })
  searchData()
}
const {
  tableData,
  columns,
  isLoading: loading,
  paginationState: pagination,
  onPageSizeChange: handleSizeChange,
  onCurrentPageChange: handleCurrentChange,
  searchState, // 搜索参数
  searchData,
  resetSearch
} = useTable<any>({
  core: {
    apiFn: BmslzService.userList,
    apiParams: {
      pageSize: 10,
      pageNo: 1,
    },
    paginationKey: {
      current: 'pageNo',
      size: 'pageSize'
    },
    columnsFactory: () => [
      {
        prop: 'id',
        label: '用户id'
      },
      {
        prop: 'username',
        label: '用户名'
      },
      {
        prop: 'name',
        label: '真实姓名',
      },
      {
        prop: 'role',
        label: '角色',
      },
      {
        prop: 'orderCloseTime',
        label: '订单失效时间',
      },
      {
        prop: 'createTime',
        label: '创建时间',
        useSlot: true,
      },
      {
        prop: 'operation',
        label: '操作',
        width: 90,
        useSlot: true,
        fixed: 'right'
      }
    ]
  }
})
</script>

<style lang="scss" scoped>
.parent {
  padding: 0 0 0 20px;

  .title {
    color: #101010;
    font-size: 20px;
    font-weight: bold;
  }

  .title2 {
    color: #101010;
    font-size: 15px;
    font-weight: bold;
  }
}
</style>